'use client';
import Breadbar from '@/components/Breadbar';
import { useClientParams, useGlobalState } from '@/hooks';
import './index.scss';
import FiltersMod from './components/FiltersMod';
import TitleMod from './components/TitleMod';
import ToolsBarMod from './components/ToolsBarMod';
import ProductList from './components/ProductList';
import FilterTags from './components/FilterTags';
import { parseUrlToFetchParams, staticGo } from '@/utils/common';
import { useEffect, useRef, useState } from 'react';
import { showLoading } from '@/components/ContentLoading';
import { getServerSideProducts } from '@/services/back';
import { getProducts } from '@/services';
import CategoryCarousel from './components/CategoryCarousel';
import CategoryDesciption from './components/CategoryDesciption';
import CompareListSection from './components/CompareListSection';

type pageProps = {
  params: {
    slug?: string[];
  };
  searchParams: Obj<any>;
  category: Obj<any> | null;
  categories: any[];
  products: Obj<any> | null;
  paths: string[];
  pageTitle: string;
  filters?: Obj<any>;
};
const Categories = (props: pageProps) => {
  const { category, products, paths, pageTitle, categories } = props;
  const { isLogin } = useGlobalState('main');
  const {
    basePath,
    pathname,
    queryObject,
    catePaths,
    searchParams,
    paramsObject,
    categoryObject,
    filterObject,
  } = useClientParams();

  const gotoPage = (page: number) => {
    staticGo(pathname, { ...queryObject, p: '' + page }, true);
  };
  const changePageSize = (pageSize: number) => {
    queryObject.p && delete queryObject.p;
    staticGo(pathname, { ...queryObject, limit: '' + pageSize }, true);
  };

  const [clientProducts, setClientProducts] = useState<any>({});
  const [isLoading, setIsLoading] = useState(true);
  // const [selectedList, setselectedList] = useState<any[]>([]);

  const handleSelectChange = (pList: any[]) => {
    const newProducts = { ...clientProducts, result: pList };
    setClientProducts(newProducts);
  };
  const [isShowFilter, setIsShowFilter] = useState(false);
  const handleOpenFilter = () => {
    setIsShowFilter(true);
  };
  const handleCloseFilter = () => {
    setIsShowFilter(false);
  };
  const [isShowCompareList, setIsShowCompareList] = useState(false);
  const handleOpenCompareList = () => {
    setIsShowCompareList(true);
  };
  const handleCloseCompareList = () => {
    setIsShowCompareList(false);
  };

  const checkQueryParams = () => {
    if (!isLogin) {
      const newQueryObject = { ...queryObject };
      const publicKeys = ['limit', 'p'];
      const limitKeys =
        basePath == 'catalogsearch' ? [...publicKeys, 'q'] : [...publicKeys];
      const queryObjKeys = Object.keys(newQueryObject);
      let hasInvalidKey = false;
      queryObjKeys.forEach(key => {
        if (!limitKeys.includes(key)) {
          hasInvalidKey = true;
          delete newQueryObject[key];
        }
      });
      return hasInvalidKey ? newQueryObject : false;
    }
    return false;
  };
  const checkQueryParamsRef = useRef(checkQueryParams);
  checkQueryParamsRef.current = checkQueryParams;

  const queryList = async () => {
    const checkQuery = checkQueryParamsRef.current();
    if (checkQuery) staticGo(pathname, { ...checkQuery }, true);

    const hideLoading = showLoading({
      inner: false,
      mask: true,
      maskStyle: { backgroundColor: 'rgba(255,255,255,.05)' },
      style: {
        // marginLeft: '310px',
        marginTop: '200px',
      },
    });
    setIsLoading(true);
    const queryParams = parseUrlToFetchParams(
      basePath,
      catePaths,
      queryObject,
      categories
    );
    // console.log('=============================================');
    // console.log(
    //   basePath,
    //   pathname,
    //   catePaths,
    //   queryObject,
    //   categories?.length,
    //   queryParams,
    //   categoryObject,
    //   filterObject
    //   // categories
    // );
    const skusInfo = (await getProducts(queryParams).catch(e => {
      void e;
    })) || { result: [], total: 0, hasError: true };
    if (skusInfo?.result?.length) {
      skusInfo.result.forEach((item: Obj) => {
        item.original_on_my_sku_list = item?.on_my_sku_list;
      });
    }
    // console.log(skusInfo);
    setClientProducts(skusInfo);
    hideLoading();
    setIsLoading(false);
  };
  const queryListRef = useRef(queryList);
  queryListRef.current = queryList;

  useEffect(() => {
    if (basePath) {
      queryListRef.current();
    }
  }, [basePath, catePaths, queryObject]);

  const currentPaths = catePaths?.length ? catePaths : paths;

  // const currentProducts = clientProducts || products;
  const handleAddedToMySkuList = (skus: any[]) => {
    const pList = clientProducts?.result;
    if (pList?.length) {
      pList.forEach((p: any) => {
        if (skus.includes(p.sku)) {
          p.on_my_sku_list = true;
          p.original_on_my_sku_list = true;
        }
      });
      const newProducts = { ...clientProducts, result: pList };
      setClientProducts(newProducts);
    }
  };

  return (
    <div className="main">
      <div className="main-wrapper">
        <Breadbar paths={currentPaths} basePath={basePath} />
        <TitleMod pageTitle={pageTitle} basePath={basePath} />
        <CategoryCarousel />
        <div className="content-wrapper">
          <div className="content-sidebar">
            <FiltersMod
              paths={currentPaths}
              basePath={basePath}
              isLogin={isLogin}
              isShowFilter={isShowFilter}
              onCloseFilter={handleCloseFilter}
            />
            <CompareListSection
              isLogin={isLogin}
              isShow={isShowCompareList}
              onClose={handleCloseCompareList}
            />
          </div>

          <div className="content-main">
            <ToolsBarMod
              products={clientProducts}
              isLogin={isLogin}
              onSelectChange={handleSelectChange}
              onOpenFilter={handleOpenFilter}
              onOpenCompareList={handleOpenCompareList}
              // hide={basePath == 'catalogsearch' && !clientProducts?.length}
              onAddedToMySkuList={handleAddedToMySkuList}
            />
            {isLogin && <FilterTags />}
            <ProductList
              basePath={basePath}
              products={clientProducts}
              onGoPage={gotoPage}
              onChangePageSize={changePageSize}
              isLoading={isLoading}
              isLogin={isLogin}
              onSelectChange={handleSelectChange}
            />
            <CategoryDesciption
              basePath={basePath}
              currentCategory={categoryObject}
            />
          </div>
        </div>
      </div>
    </div>
  );
};

export default Categories;
